import React, { useState, useEffect } from 'react'
import { Save, Activity, CheckCircle, XCircle } from 'lucide-react'
import { settingsApi, KsqlConfig as KsqlConfigType } from '@/services/settings'
import toast from 'react-hot-toast'

export default function KsqlConfig() {
  const [ksqlConfig, setKsqlConfig] = useState<KsqlConfigType>({
    ksql_server_url: 'http://localhost:8088',
    ksql_username: '',
    ksql_password: '',
    ksql_timeout: 30000,
    ksql_enabled: false
  })

  const [ksqlTesting, setKsqlTesting] = useState(false)
  const [ksqlSaving, setKsqlSaving] = useState(false)
  const [ksqlTestResult, setKsqlTestResult] = useState<{ success: boolean; message: string } | null>(null)

  // 加载KSQL配置
  useEffect(() => {
    const loadKsqlConfig = async () => {
      try {
        const ksqlConfigData = await settingsApi.getKsqlConfig()
        setKsqlConfig(ksqlConfigData)
      } catch (error) {
        console.error('从后端加载KSQL配置失败:', error)
        // 如果后端加载失败，尝试从localStorage加载
        const savedKsqlConfig = localStorage.getItem('ksql_config')
        if (savedKsqlConfig) {
          try {
            const parsedKsqlConfig = JSON.parse(savedKsqlConfig)
            setKsqlConfig(parsedKsqlConfig)
          } catch (error) {
            console.error('加载KSQL配置失败:', error)
          }
        }
      }
    }

    loadKsqlConfig()
  }, [])

  const handleKsqlInputChange = (field: string, value: string | number | boolean) => {
    setKsqlConfig(prev => ({
      ...prev,
      [field]: value
    }))
    setKsqlTestResult(null) // 清除测试结果
  }

  const testKsqlConnection = async () => {
    setKsqlTesting(true)
    setKsqlTestResult(null)

    try {
      const result = await settingsApi.testKsqlConnection(ksqlConfig)
      setKsqlTestResult(result)
      
      if (result.success) {
        toast.success('KSQL连接测试成功')
      } else {
        toast.error('KSQL连接测试失败')
      }
    } catch (error: any) {
      setKsqlTestResult({
        success: false,
        message: `KSQL连接失败: ${error.message || '网络错误'}`
      })
      toast.error('KSQL连接测试失败')
    } finally {
      setKsqlTesting(false)
    }
  }

  const saveKsqlConfig = async () => {
    setKsqlSaving(true)

    try {
      // 保存KSQL配置到后端Redis
      await settingsApi.saveKsqlConfig(ksqlConfig)

      // 同时保存到localStorage作为备份
      localStorage.setItem('ksql_config', JSON.stringify(ksqlConfig))

      toast.success('KSQL配置保存成功')
    } catch (error) {
      toast.error('KSQL配置保存失败')
    } finally {
      setKsqlSaving(false)
    }
  }

  return (
    <div className="card">
      <div className="card-header">
        <h2 className="card-title">KSQL配置</h2>
        <p className="card-description">
          配置KSQL服务器连接信息，用于流处理查询
        </p>
      </div>
      <div className="card-content space-y-6">
        {/* 启用KSQL */}
        <div className="flex items-center space-x-3">
          <input
            type="checkbox"
            id="ksql_enabled"
            checked={ksqlConfig.ksql_enabled}
            onChange={(e) => handleKsqlInputChange('ksql_enabled', e.target.checked)}
            className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
          />
          <label htmlFor="ksql_enabled" className="text-sm font-medium text-gray-700">
            启用KSQL功能
          </label>
        </div>

        {ksqlConfig.ksql_enabled && (
          <div className="space-y-4">
            {/* KSQL服务器URL */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                KSQL服务器URL
              </label>
              <input
                type="text"
                value={ksqlConfig.ksql_server_url}
                onChange={(e) => handleKsqlInputChange('ksql_server_url', e.target.value)}
                placeholder="http://localhost:8088"
                className="input"
              />
              <p className="text-xs text-gray-500 mt-1">
                KSQL服务器的完整URL地址
              </p>
            </div>

            {/* 认证信息 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  用户名（可选）
                </label>
                <input
                  type="text"
                  value={ksqlConfig.ksql_username}
                  onChange={(e) => handleKsqlInputChange('ksql_username', e.target.value)}
                  placeholder="输入KSQL用户名"
                  className="input"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  密码（可选）
                </label>
                <input
                  type="password"
                  value={ksqlConfig.ksql_password}
                  onChange={(e) => handleKsqlInputChange('ksql_password', e.target.value)}
                  placeholder="输入KSQL密码"
                  className="input"
                />
              </div>
            </div>

            {/* 超时设置 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                连接超时（毫秒）
              </label>
              <input
                type="number"
                value={ksqlConfig.ksql_timeout}
                onChange={(e) => handleKsqlInputChange('ksql_timeout', parseInt(e.target.value) || 30000)}
                placeholder="30000"
                className="input"
                min="1000"
                max="300000"
              />
              <p className="text-xs text-gray-500 mt-1">
                KSQL查询的超时时间，建议30秒
              </p>
            </div>

            {/* KSQL测试结果 */}
            {ksqlTestResult && (
              <div className={`p-4 rounded-md ${
                ksqlTestResult.success ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'
              }`}>
                <div className="flex items-center">
                  {ksqlTestResult.success ? (
                    <CheckCircle className="h-5 w-5 text-green-500 mr-2" />
                  ) : (
                    <XCircle className="h-5 w-5 text-red-500 mr-2" />
                  )}
                  <span className={`text-sm font-medium ${
                    ksqlTestResult.success ? 'text-green-800' : 'text-red-800'
                  }`}>
                    {ksqlTestResult.message}
                  </span>
                </div>
              </div>
            )}

            {/* KSQL测试按钮 */}
            <div className="flex space-x-3">
              <button
                onClick={testKsqlConnection}
                disabled={ksqlTesting || !ksqlConfig.ksql_server_url}
                className="btn-secondary"
              >
                <Activity className={`h-4 w-4 mr-2 ${ksqlTesting ? 'animate-spin' : ''}`} />
                {ksqlTesting ? '测试中...' : '测试KSQL连接'}
              </button>
            </div>
          </div>
        )}

        {/* 保存按钮 */}
        <div className="flex justify-end">
          <button
            onClick={saveKsqlConfig}
            disabled={ksqlSaving}
            className="btn-primary"
          >
            <Save className={`h-4 w-4 mr-2 ${ksqlSaving ? 'animate-spin' : ''}`} />
            {ksqlSaving ? '保存中...' : '保存KSQL配置'}
          </button>
        </div>
      </div>
    </div>
  )
}
